/**
 * Copyright (C) 2012 The SkyTvOS Project
 * <p/>
 * Version     Date           Author
 * ─────────────────────────────────────
 * 2014年11月18日         Root.Lu
 */

package com.tianci.appstore.utils;

import android.os.Handler;
import android.os.Looper;

public class HandlerThread extends Thread {
    private Handler handler = null;
    private Looper looper = null;

    public HandlerThread(String name) {
        super(name);
        setPriority(Thread.MIN_PRIORITY);
    }

    public HandlerThread(ThreadGroup tg, String name) {
        super(tg, name);
        setPriority(Thread.MIN_PRIORITY);
    }

    @Override
    public void run() {
        // TODO Auto-generated method stub
        Looper.prepare();
        synchronized (this) {
            looper = Looper.myLooper();
            handler = new Handler(looper);
            notify();
        }
        Looper.loop();
        synchronized (this) {
            looper = null;
            handler = null;
        }
    }

    public void shutdown() {
        synchronized (this) {
            if (looper != null)
                looper.quit();
        }
    }

    public void postAction(Runnable run) {
        synchronized (this) {
            if (handler == null) {
                try {
                    wait();
                } catch (InterruptedException e) {
                    // TODO Auto-generated catch block
                    e.printStackTrace();
                }
            }
        }
        handler.post(run);
    }
}
